package com.crazymaker.agent.demo.javassist;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class Transformer implements ClassFileTransformer {

    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        byte[] bytes = null;
        if (className.equals("com/crazymaker/circle/agent/Helloworld")) {
            try {
                ClassPool classPool = ClassPool.getDefault();
                CtClass cc = classPool.get("com.crazymaker.circle.agent.Helloworld");
                CtMethod method = cc.getDeclaredMethod("sayHello");
                method.insertBefore("{ System.out.println(\"begin of sayhello()\"); }");
                method.insertAfter("{ System.out.println(\"end of sayhello()\"); }");
                bytes = cc.toBytecode();
                log("class transformed = %s", className);
            } catch (Exception e) {
                log("a exception happened when transforming class = %s", className);
            }
        } else {
            log(className + "   transforming skip, not the target class.");
        }

        return bytes;
    }

    private void log(String s) {

        System.out.println("AopTransformer:" + s);

    }

    private void log(String s, String className) {

        System.out.println(className + ":" + s);

    }
}